package com.zhanglinwei.openApiClient.segment;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.zhanglinwei.common.constants.StringPoolConstant.*;

@Getter
@Setter
public class WhereSegment implements SQLSegment{

    private final List<String> whereSegmentList = new ArrayList<>();

    @Override
    public boolean isEmpty() {
        return CollectionUtils.isEmpty(whereSegmentList);
    }

    public void removeLastIf(Predicate<String> condition) {
        if (isEmpty()) {
            return;
        }

        int lastIndex = whereSegmentList.size() - 1;
        String lastElement = whereSegmentList.get(lastIndex);

        if (condition == null || condition.test(lastElement)) {
            whereSegmentList.remove(lastIndex);
        }
    }

    public void removeLastLogicOperator() {
        removeLastIf(item -> item.equals(SQLKeyword.AND.sqlSegment()) || item.equals(SQLKeyword.OR.sqlSegment()));
    }

    public Set<String> columns() {
        return isEmpty() ? Collections.emptySet() : whereSegmentList.stream()
                .filter(item -> !SQLKeyword.matchSegment(item))
                .filter(item -> !item.startsWith(HASH_LEFT_BRACE))
                .filter(item -> !LEFT_BRACKET.equals(item) && !RIGHT_BRACKET.equals(item))
                .collect(Collectors.toSet());
    }

    public void addAll(WhereSegment whereSegment) {
        if (whereSegment == null || whereSegment.isEmpty()) {
            return;
        }

        this.whereSegmentList.addAll(whereSegment.getWhereSegmentList());
    }

    @Override
    public void add(SQLSegment... sqlSegments) {
        if (ArrayUtils.isNotEmpty(sqlSegments)) {
            Arrays.asList(sqlSegments).forEach(item -> whereSegmentList.add(item.sqlSegment()));
        }
    }

    @Override
    public String sqlSegment() {
        return SQLKeyword.WHERE.sqlSegment() + " " + String.join(" ", whereSegmentList);
    }
}
